<template>
  <div class="avatarPop">
    <img :src="src" class="img" ref="image" />

    <div class="toolBar">
      <div @click="$emit('close')">取消</div>
      <div @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { getImgUrl } from '@/assets/api/user'
export default {
  name: 'avatarPop',
  props: {
    src: {
      tyle: [String, Object],
      required: true
    }
  },
  data() {
    return {
      cropper: null
    }
  },
  methods: {
    onConfirm() {
      // 服务端处理用getData
      // 纯客户端处理
      this.cropper.getCroppedCanvas().toBlob(async (blob) => {
        this.$toast.loading({
          message: '保存中',
          forbidClick: true,
          // 持续展示
          duration: 0
        })
        const formData = new FormData()
        formData.append('photo', blob)
        try {
          // axios会自动设置
          var { data: res } = await getImgUrl(formData)
        } catch {
          this.$toast('裁剪图片失败稍后再试')
          return this.$emit('close')
        }
        this.$toast('更新成功')
        this.$emit('finish', res.data.photo)
      })
    }
  },
  mounted() {
    const image = this.$refs.image
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false
    })
  }
}
</script>

<style lang="less" scoped>
.avatarPop {
  position: relative;
  height: 100%;
  background-color: #000;
  .toolBar {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    div {
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
  .img {
    position: absolute;
  }
}
.img {
  display: block;
  max-width: 100%;
}
</style>
